/**
 * 该文件为路由接口--对应螃蟹市场的相关接口
 */

/**
 * 引入相关配置
 */
const express=require("express");
const router=express.Router();

// 引入数据库model
const CrabModel=require("../../../models/futureMarket/Crab.js");

// 引入passport模块
const passport=require("passport");

//引入全局输出类
const JsonResult=require("../../global/JsonResult.js");

// 引入图片上传路径模块
const upload=require("../../../middleware/uploadMultipleImage.js");
const multer=require("multer");

// 引入查询条件和配置项
const UnityParams=require("../../conditions/unityParams.js");

/**
 * 路由接口定义
 */
// 添加螃蟹市场接口（/api/crab/add）
router.post("/add",passport.authenticate("jwt",{session:false}),(req,res,next)=>{
    upload.array("images",6)(req,res,(err)=>{
        if(err instanceof multer.MulterError){
            // console.log(err.message);
            if(err.message === "File too large"){
                res.json(JsonResult.middlewareFail("图片大小不得超过20M",null));
            }else{
                res.json(JsonResult.middlewareFail("发生错误",null));
            };
        }else if(err){
            res.json(JsonResult.middlewareFail(err.message,null));
        }else{
            console.log(req.body,req.files);
        };
    });
});

// 查询螃蟹市场接口（/api/crab）
router.get("/",passport.authenticate("jwt",{session:false}),async (req,res,next)=>{
    let counts=UnityParams.counts;
    let unityDataObj=UnityParams.unityDataObj(req.query);
    let unityOptionsObj=UnityParams.unityOptionsObj({...req.query,sort:{type:1}});
    counts=await CrabModel.countDocuments();
    CrabModel.find(unityDataObj,null,unityOptionsObj).then((doc)=>{
            res.json(JsonResult.success("查询成功",{
                currentPage:req.query.pageNum?req.query.pageNum:1,
                currentSize:req.query.pageSize?req.query.pageSize:5,
                total:counts,
                data:doc
        }));
    }).catch((err)=>{
        console.log(err);
        res.status(500).json(JsonResult.databaseError("查询螃蟹信息出错",null));
    });
});

module.exports=router;